package com.example.demo.tool.netty.chat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class ChatServer {

    public static void main(String[] args) throws InterruptedException {
        // 创建2个线程组
        // 主线程用来处理客户端的连接，并将其注册到子线程的Selector里去
        EventLoopGroup group = new NioEventLoopGroup(1);
        // 默认线程数是cpu核数的2倍
        // 子线程主要将处理连接之后的读写操作
        EventLoopGroup worker = new NioEventLoopGroup();

        try {
            // 创建服务端的启动对象
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(group, worker)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline()
                            // 自定义编码器
                            .addLast(new MyMessageDecoder())
                            // 自定义解码器
                            .addLast(new MyMessageEncoder())
                            // 添加ChatServerHandler要在编码解码后面，否则可能导致无法收消息。因为一定要解码之后，才能给Handler处理
                            // 否则重写的channelRead0是无法直接处理String等类型的消息
                            // 解码之后，交给ChatServerHandler处理
                            .addLast(new ChatServerHandler());
                        }
                    });

            System.out.println("聊天服务器启动中...");

            ChannelFuture cf = bootstrap.bind(9000).sync();

            cf.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
            worker.shutdownGracefully();
        }


    }
}

